package bg.btanev.eightyfour.domain.experience;

import org.apache.commons.lang.Validate;

import bg.btanev.eightyfour.domain.entitybase.DomainEntity;
import bg.btanev.eightyfour.domain.experience.institution.Institution;
import bg.btanev.eightyfour.domain.person.Person;

/**
 *
 * @author B.Tanev
 *
 * @param <EI>
 *            an {@link Institution} type.
 */
public abstract class Experience<EI extends Institution> extends DomainEntity<Long> implements Comparable<Experience<EI>> {
	/**
	 *
	 */
	private static final long serialVersionUID = 8017167654153323289L;

	private ExperiencePeriod period; // component
	private EI institution; // many-to-one

	private Person person; // reference to parent Person

	protected Experience() {
		super();
	}

	public Experience(ExperiencePeriod period, EI institution, Person person) {
		this(null, period, institution, person);
	}

	public Experience(Long id, ExperiencePeriod period, EI institution, Person person) {
		super(id);

		Validate.notNull(period);
		Validate.notNull(institution);
		Validate.notNull(person);

		this.period = period;
		this.institution = institution;

		updatePerson(person);
	}

	private boolean updatePerson(Person person) {
		assert (person != null);

		this.person = person;
		this.person = updatePersonInternal(person);
		return this.person != null;
	}

	public ExperiencePeriod getPeriod() {
		return period;
	}

	public EI getInstitution() {
		return institution;
	}

	public Person getPerson() {
		return person;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((period == null) ? 0 : period.hashCode());
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Experience other = (Experience) obj;
		if (period == null) {
			if (other.period != null)
				return false;
		} else if (!period.equals(other.period))
			return false;
		return true;
	}

	@Override
	public int compareTo(Experience<EI> o) {
		return this.period.compareTo(o.period);
	}

	protected abstract Person updatePersonInternal(Person person);
}
